from django.shortcuts import render

# Create your views here.
# from rest_framework.mixins import UpdateModelMixin, CreateModelMixin
from rest_framework.generics import CreateAPIView, UpdateAPIView, ListAPIView, DestroyAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ViewSetMixin

import constants
from address import serializers
from address.models import Address


class AddressGetAPIView(CreateAPIView, ListAPIView, UpdateAPIView, DestroyAPIView):
	permission_classes = [IsAuthenticated]

	def get_queryset(self):
		user = self.request.user
		return Address.objects.filter(is_deleted=False, user=user)

	serializer_class = serializers.AddressGetSerializer

	# 删除地址是用Destory中默认的destory方法
	# 修改地址信息是用Update中的update方法
	# 新建用户是用Create中的Create方法

	# 显示所有地址
	def list(self, request, *args, **kwargs):
		user = self.request.user
		data = {'address': serializers.AddressGetSerializer(user.addresses, many=True).data,
		        'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
		        'default_address_id': user.default_address_id}

		return Response(data, status=200)


class AddressChangeTitleAPIView(ViewSetMixin, UpdateAPIView,):
	"""
	更改title标题
	"""

	# 设置用户默认地址
	def default(self, request, *args, **kwargs):
		user = request.user
		address = self.get_object()
		user.default_address_id = address
		user.save()
		return Response({'message': 'ok'})

	# 序列化方式实现Title的修改
	def get_queryset(self):
		user = self.request.user
		return Address.objects.filter(is_deleted=False, user=user)

	serializer_class = serializers.AddressChangeTitleSerializer

	# # 不用序列化器直接实现，因为传入的参数不需要序列化
	# def put(self, request, *args, **kwargs):
	# 	title = request.data.get('title')
	# 	pk = self.kwargs.get('pk')
	#
	# 	address = None
	# 	try:
	# 		address = Address.objects.get(id=pk)
	# 	except Exception as e:
	# 		Response({"message":"传入的pk参数有误"},status=401)
	# 	else:
	# 		pass
	#
	# 	address.title = title
	# 	address.save()
	# 	return Response(serializers.AddressGetSerializer(address).data)

